package com.didi.gulimall.job;

/**
 * @Author 10626
 * @Create 2021/6/4 17:28
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.didi.gulimall.common.constant.RabbitMqConstant;
import com.didi.gulimall.common.entity.LocalMqEntity;
import com.didi.gulimall.ware.service.LocalMqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * @Author 10626
 * @Create 2021/6/4 15:01
 */
//@Configuration
//@EnableScheduling
@Slf4j
public class MessageSending {

    @Autowired
    private LocalMqService localMqService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 消息重发 每一分钟扫描一次消息未处理的消息 并重试次数小于指定次数 重新发送
     */
    @Scheduled(cron = "0,30 0/1 * * * ? ")
    private void configureTasks() {
        QueryWrapper<LocalMqEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", RabbitMqConstant.NOT_CONSUMED);
        wrapper.le("retries", RabbitMqConstant.MAXIMUM_NUMBER_OF_RETRIES);
        List<LocalMqEntity> localMqEntities = localMqService.list(wrapper);
        log.info("扫描为消耗的消息共计:{}条", localMqEntities.size());
        if (CollectionUtils.isNotEmpty(localMqEntities)){
            for (LocalMqEntity localMqEntity : localMqEntities) {
                localMqEntity.setRetries(localMqEntity.getRetries() + 1);
                rabbitTemplate.convertAndSend(localMqEntity.getExchange(), localMqEntity.getRouteKey(), localMqEntity.getBody(), new CorrelationData(localMqEntity.getId()));
            }
            localMqService.updateBatchById(localMqEntities);
        }
    }
}